<?php
//initialize the session
session_start(); 
require_once('Connections/db.php');
require_once('funciones/funciones.php');

// set the error reporting level for this script
error_reporting  (E_USER_ERROR + E_USER_WARNING + E_USER_NOTICE);
// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");

// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  session_unregister('MM_Username');
  session_unregister('MM_UserGroup');
	
  $logoutGoTo = "index.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
$mostrardatospago = -1;
$nropago = -1;
if (isset($_POST['nropago']) && ($_POST['nropago'] != ''))  {
	$nropago = $_POST['nropago'];
	$aniopago = $_POST['anio']; }
elseif (isset($_GET['nropago']) && ($_GET['nropago'] != '')) {
	$nropago = $_GET['nropago'];
	$aniopago = $_GET['anio']; }

if ($nropago != -1) {
	mysql_select_db($database_db, $db);
	$query_qrypagos = "select p.*, d.`nombre` as despachantenombre, sum(importe_pago_sol) as imppagossol 
		from pagos p 
		inner join `despachantes` d on (p.`despachante_cuit` = d.`cuit_cuil`) 
		left join pagos_solicitud s on (p.`id_pago` = s.`id_pago`)
		where anio_pago = ".$aniopago." and p.`nro_pago` = ".$nropago."  
		group by p.`id_pago`";

	$qrypagos = mysql_query($query_qrypagos, $db) or die(mysql_error());
	$row_qrypagos = mysql_fetch_assoc($qrypagos);	
	$impsinafectar = number_format($row_qrypagos['importe_pago'] - $row_qrypagos['imppagossol'],2);
	
	$totalRows_qrypagos = mysql_num_rows($qrypagos);
	if ($totalRows_qrypagos > 0 )
		$mostrardatospago = 1;
	else
		$mostrardatospago = 0;
	
	mysql_select_db($database_db, $db);
	$query_qryliq = "select distinct s.`nro_liquidacion` from `solicitud_servicios` s  where s.`pagado` = 0 and s.`nro_liquidacion` is not null  and s.`despachante_cuit` = '".$row_qrypagos['despachante_cuit']."' Order by nro_liquidacion";
	$qryliq = mysql_query($query_qryliq, $db) or die(mysql_error());
	$row_qryliq = mysql_fetch_assoc($qryliq);
	$totalRows_qryliq = mysql_num_rows($qryliq);
	
	$query_qrysolicitudes = '';
}
if (isset($_POST['selliquidacion']) && ($_POST['selliquidacion'] != '') ) {

if ($_POST['despachantecuit'] != $row_qrypagos['despachante_cuit']) 
	$despcuit = $row_qrypagos['despachante_cuit'];
else
	$despcuit = $_POST['despachantecuit'];
	
mysql_select_db($database_db, $db);
	$query_qrysolicitudesTot = "select sum( d.`importe` + d.`importe_comidas`) as imptotalsol  
						from `solicitud_servicios` s
						inner join `solicitud_servicios_det` d on (s.`id_solicitud` = d.`id_solicitud`)
						where s.`pagado` = 0 and s.`nro_liquidacion` = ".$_POST['selliquidacion']." 
						and s.`despachante_cuit` = '".$despcuit."'";
	$qrysolicitudesTot = mysql_query($query_qrysolicitudesTot, $db) or die(mysql_error());
	$row_qrysolicitudesTot = mysql_fetch_assoc($qrysolicitudesTot);	
	
mysql_select_db($database_db, $db);
	$query_qrysolicitudes = "select s.id_solicitud, s.`nro_solicitud`, s.`fecha_inicio_estimada`, s.`operador_cuit`, s.`documentos`, s.saldo,
						 o.`nombre` as operadornombre, r.`descripcion` as regimennombre, sum( d.`importe` + d.`importe_comidas`) as imptotal 
						from `solicitud_servicios` s
						inner join `operadores` o on (s.`operador_cuit` = o.`cuit_cuil_dni`)
						inner join `regimen` r on (s.`cod_regimen` = r.`cod_regimen`)
						left join `solicitud_servicios_det` d on (s.`id_solicitud` = d.`id_solicitud`)
						where s.`pagado` = 0 and s.`nro_liquidacion` = ".$_POST['selliquidacion']." 
						and s.`despachante_cuit` = '".$despcuit."' 
						group by s.id_solicitud, s.`nro_solicitud`, s.`fecha_inicio_estimada`, s.`operador_cuit`, s.`documentos`,
						o.`nombre`, r.`descripcion`";
//echo $query_qrysolicitudes;						
	$qrysolicitudes = mysql_query($query_qrysolicitudes, $db) or die(mysql_error());
	$row_qrysolicitudes = mysql_fetch_assoc($qrysolicitudes);
	$totalRows_qrysolicitudes = mysql_num_rows($qrysolicitudes);							
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><!-- InstanceBegin template="/Templates/menu.dwt.php" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<!-- InstanceBeginEditable name="doctitle" -->
<title>Aduana</title>
<script language="JavaScript" src="funciones.js"></script>
<script language="javascript" type="text/javascript">
<!--
function ChkSelItem(icantchecks, idpago) {
	if (document.form2.totpagos.value == 0) {
		alert('Debe seleccionar las solicitudes afectadas por el pago'); }
	else if (document.form2.pagos_graba.value == 0) {
		alert('El importe de las solicitudes seleccionadas es mayor al importe a afectar'); }
	else {	
		//recorrer todos los checks y tomar el importe del edit, por cada uno llamar a una pag para 
		//hacer el update de solicitudes -> pagado=1
		for (i=0; i<icantchecks;i++) {
			nombrechk = 'chk'+i;
			idsol = 'idsol'+i;			
			impsolsaldo = 'impsolsaldo'+i;
			
			if (document.getElementById(nombrechk).checked) { 
				edpago = 'ed'+i;
				urlparam = 'pagos_det_upd.php?idsol='+document.getElementById(idsol).value+'&idpago='+idpago+'&importepago='+document.getElementById(edpago).value+'&impsol='+document.getElementById(impsolsaldo).value;
				//alert( urlparam);
				window.open(urlparam, '','scrollbars=no,height=1,width=1,dependent=yes');
			}
		}		
		location.href = 'pagos_det.php?anio='+document.form1.anio.value+'&nropago='+document.form1.nropago.value;
	}
}
//Calculo el monto total de los pagos de las solicitudes seleccionadas: 
function CalcTotPagos(icantchecks, idsol) {
	document.form2.totpagos.value = 0;
	document.form2.totresto.value = 0;
//	var totpagos = new oNumero( 0);
//	alert(icantchecks);
	for (i=0; i<icantchecks;i++) {
//		nombrechk = 'chk'+idsol;
		nombrechk = 'chk'+i;
		if (document.getElementById(nombrechk).checked) { 		
//			edpago = 'ed'+idsol;
			edpago = 'ed'+i;
//			alert('edpago: '+document.getElementById(edpago).value + '  - totpagos: '+document.form2.totpagos.value + '  - i: ' + i);
			document.form2.totpagos.value = Number(document.form2.totpagos.value) + Number(document.getElementById(edpago).value);

//			totpagos = totpagos + Number(document.getElementById(edpago).value);
//			document.form2.totpagos.value = totpagos.formato(0,false);
//			alert('totpagos: '+document.form2.totpagos.value);

			document.form2.pagos_graba.value = 1;
			document.form2.totresto.value = Number(document.form1.impsinafectar.value) - Number(document.form2.totpagos.value);
			if ( Number(document.form2.totpagos.value) > Number(document.form1.impsinafectar.value)) {
//alert('La suma de los importes de las solicitudes seleccionadas es mayor al importe a afectar'); 
				//document.getElementById(nombrechk).checked = false;
				//document.form2.totpagos.value = Number(document.form2.totpagos.value) - Number(document.getElementById(edpago).value);
				document.form2.pagos_graba.value = 0;
			}	
		} 
		/*else {
			document.form2.totpagos.value = Number(document.form2.totpagos.value) - Number(document.getElementById(edpago).value);
		}*/
	}
}
function gotofocus() {
	document.form1.anio.focus();
}
//-->
</script>
<!-- InstanceEndEditable --><!-- InstanceBeginEditable name="head" --><!-- InstanceEndEditable -->
<link href="aduana.css" rel="stylesheet" type="text/css">
<script language="JavaScript" type="text/JavaScript">
<!-- 

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
 

//-->
</script>
<style type="text/css">
<!--
body {

}
.style1 {color: #FFFFFF}
-->
</style>
<!-- InstanceParam name="OptionalRegion1" type="boolean" value="true" --><!-- InstanceParam name="OptionalRegion2" type="boolean" value="true" --><!-- InstanceParam name="OptionalRegion3" type="boolean" value="true" -->
</head>

<body onLoad="gotofocus()">
<table width="720" height="100%" border="2" align="center" cellpadding="0" cellspacing="0" bordercolor="#333399">
  <tr>
    <td valign="top"><table width="780" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td width="600" valign="middle">&nbsp;</td>
        <td><table width="180" height="60" border="0" cellpadding="0" cellspacing="1" bgcolor="#757B93">
            <tr>
              <td bgcolor="#bdbdbd"><div align="center" class="logout_usr">
			    <?php if (isset($_SESSION['MM_Username'])) {
				?>
			    <a href="<?php echo $logoutAction ?>" class="logout_usr">
					<?php  echo 'logout: '.$_SESSION['MM_Username']; ?>
				  </a>			  	
			    <?php } else {?>
				  <a href="index.php" class="negritaBlanca">Login</a></div></td> 
			  <?php } ?>
            </tr>
            <tr>
              <td height="20" class="titulo_adm_actual"><!-- InstanceBeginEditable name="titulo_adm_actual" -->
                <div align="center">Pagos</div>
              <!-- InstanceEndEditable --></td>
            </tr>
        </table></td>
      </tr>
    </table>
      
      <table width="780" height="20" border="0" cellpadding="0" cellspacing="1" bgcolor="#1B01A9">
        <tr bgcolor="#000099">
		<?php if (isset($_SESSION['MM_Username']) ) { 
			echo '<td bgcolor="#757B93">&nbsp;<a href="servicio_add.php" class="menu_principal">Servicios</a>&nbsp;| &nbsp;<a href="liquidaciones.php" class="menu_principal">Liquidaciones</a>&nbsp;| &nbsp;<a href="pagos.php" class="menu_principal">Pagos</a>&nbsp;| &nbsp;<a href="basicos.php" class="menu_principal">Tablas</a>&nbsp;| &nbsp;<a href="agentes.php" class="menu_principal">Agentes</a>&nbsp;| &nbsp; <a href="informes.php" class="menu_principal">Informes</a>&nbsp;| &nbsp; <a href="permisos.php" class="menu_principal">Seguridad</a> </td>';
		} else {  
			echo '<td bgcolor="#757B93" class="menu_principal">&nbsp;Servicios &nbsp;| &nbsp;Liquidaciones&nbsp;| &nbsp;Pagos&nbsp;| &nbsp;Despachantes&nbsp;| &nbsp;Operadores &nbsp;| &nbsp;Lugares &nbsp;| &nbsp;Agentes&nbsp;| &nbsp;Seguridad</td>';						
		}?>
		<td width="178" class="negritaBlanca style1"><div align="center">
              <SCRIPT language=JavaScript><!--
function y2k(number) { return (number < 1000) ? number + 1900 : number; }
var now = new Date();
var textout; 
var month = now.getMonth();
var date = now.getDate();
var year = now.getYear();
if (month==0) textout="Enero";
if (month==1) textout="Febrero";
if (month==2) textout="Marzo";
if (month==3) textout="Abril";
if (month==4) textout="Mayo";
if (month==5) textout="Junio";
if (month==6) textout="Julio";
if (month==7) textout="Agosto";
if (month==8) textout="Septiembre";
if (month==9) textout="Octubre";
if (month==10) textout="Noviembre";
if (month==11) textout="Diciembre";
//textout += " " + date + ", " + y2k(year);
document.write (date + " de " + textout + " de " + y2k(year) );
// -->
</SCRIPT>
          </div></td>
        </tr>
      </table>
      <table width="780" height="400" border="0" cellpadding="0" cellspacing="1">
        <tr>
          <td width="140" valign="top" bgcolor="#999999"><table width="140" border="0" cellpadding="0" cellspacing="1" bgcolor="#bdbdbd">
             
              <!-- InstanceBeginEditable name="EditRegion4" -->
              <tr>
                <td height="20" bgcolor="#757B93" class="titulo_adm_actual">&nbsp;</td>
              </tr>
              <tr>
                <td height="20" bgcolor="#999999"><div align="right"><a href="pagos.php" class="menu_izquierda">Pagos</a></div></td>
              </tr>
              <tr>
                <td height="20" bgcolor="#999999"><div align="right"><a href="pagos_det.php" class="menu_izquierda">Afectar pagos</a> </div></td>
              </tr>
              <tr>
                <td height="20" bgcolor="#999999"><div align="right"><a href="inf_serv_pendientes.php" class="menu_izquierda">Informe Servicios Pend.</a> </div></td>
              </tr>
              <!-- InstanceEndEditable -->
          </table>
          <br></td>
          <td valign="top" bgcolor="#FFFFFF"><!-- InstanceBeginEditable name="EditRegion1" -->
            <form name="form1" method="post" action="">
			<br>	
              <table width="90%" height="30"  border="0" align="center" cellpadding="0" cellspacing="0">
                <tr>
                  <td width="16%" height="30" class="labels_ingreso_datos">A&ntilde;o de pago: </td>
                  <td width="9%"><input name="anio" type="text" class="cuadrodetexto" id="anio" size="6" maxlength="4" value="<?php if (isset($_POST['anio'])) { echo $_POST['anio']; } elseif (isset($_GET['anio']) ) { echo $_GET['anio']; } else { $hoy=getdate(); echo $hoy['year'];}	?>"></td>
                  <td width="14%"><span class="labels_ingreso_datos">Nro de pago: </span></td>
                  <td width="18%"><input name="nropago" type="text" class="cuadrodetexto" id="nropago" value="<?php if ( isset($_POST['nropago'])) { echo $_POST['nropago'];} elseif (isset($_GET['nropago'])) { echo $_GET['nropago'];} ?>" size="15" maxlength="15"></td>
                  <td width="43%"><input name="Submit" type="submit" class="botones" value="Buscar"></td>
                </tr>
              </table>
			<br>              
	<?php if ($mostrardatospago != -1 ) { 
				if ( $mostrardatospago == 0 ) { 
			  	echo '<span class="labels_ingreso_datos">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	 -- No se encontraron datos del pago ingresado -- </span>';
				} else { ?>
              <table width="90%"  border="0" align="center" cellpadding="0" cellspacing="0">
                <tr>
                  <td width="16%" height="19" valign="top" class="labels_ingreso_datos">Despachante:</td>
                  <td colspan="2" valign="top" class="italicaBold"><?php echo $row_qrypagos['despachantenombre'];?><span class="labels_ingreso_datos">
                    <input name="despachantecuit" type="hidden" id="despachantecuit" value="<?php echo $row_qrypagos['despachante_cuit'];?>">
                  </span></td>
                </tr>
                <tr>
                  <td height="19" valign="top" class="labels_ingreso_datos">Importe:</td>
                  <td width="33%" valign="top" class="italicaBold"><p><?php echo $row_qrypagos['importe_pago'];?>
                    <input type="hidden" name="importepago" value="<?php echo $row_qrypagos['importe_pago'];?>">
                  </p>                  </td>
                  <td valign="top" class="italicaBold"><span class="labels_ingreso_datos">Sin afectar: </span><?php echo $impsinafectar;?>
                    <input type="hidden" name="impsinafectar" value="<?php echo $impsinafectar;?>"></td>
                </tr>
                <tr>
                  <td height="21" colspan="3" class="labels_ingreso_datos">Seleccione 
                  Nro liquidaci&oacute;n: 
                  <select name="selliquidacion" class="cuadrodetexto" id="selliquidacion">
                    <?php
do {  
?>
                    <option value="<?php echo $row_qryliq['nro_liquidacion']?>"<?php if (!(strcmp($row_qryliq['nro_liquidacion'], $_POST['selliquidacion']))) {echo "SELECTED";} ?>><?php echo $row_qryliq['nro_liquidacion']?></option>
                    <?php
} while ($row_qryliq = mysql_fetch_assoc($qryliq));
  $rows = mysql_num_rows($qryliq);
  if($rows > 0) {
      mysql_data_seek($qryliq, 0);
	  $row_qryliq = mysql_fetch_assoc($qryliq);
  }
?>
                  </select>
                  &nbsp;&nbsp;&nbsp;&nbsp;<input name="Submit2" type="submit" class="botones" value="Buscar solicitudes impagas">                  </td>
                </tr>
              </table>
			  <?php } }?>
            </form>
			
			<form name="form2" method="post" action="">
			  <?php if ( $totalRows_qrysolicitudes == 0 ) {
			  	echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="italicaBold"> -- No existen solicitudes impagas --</span>';
			  } 
			  if ( ($totalRows_qrysolicitudes > 0) && ($mostrardatospago == 1) ) { // Show if recordset not empty ?>
              <table width="100%" border="0" align="center">
                <tr class="titulo_columnas_tabla" align="center">
                  <td width="10%">Nro </td>
                  <td width="12%">Fecha Servicio </td>
                  <td width="25%">Operador</td>
                  <td width="15%">Regimen</td>
                  <td width="10%">Importe</td>
                  <td width="10%">Saldo</td>
                  <td width="10%">Imp. Pago</td>
                  <td width="3%">&nbsp;</td>
                </tr>
                <?php $i = 0; do { ?>
                <tr class="contenido_columnas_tabla" align="center">
                  <td><div align="right"><?php echo $row_qrysolicitudes['nro_solicitud']; ?></div></td>
                  <td><?php $dias=explode("-",$row_qrysolicitudes['fecha_inicio_estimada']);
						echo $dias[2]."/".$dias[1]."/".$dias[0]; ?></td>
                  <td><div align="left"><?php echo $row_qrysolicitudes['operadornombre']; ?></div></td>
                  <td><div align="left"><?php echo $row_qrysolicitudes['regimennombre']; ?></div></td>
                  <td><div align="right"><?php echo $row_qrysolicitudes['imptotal']; ?>
                    <input type="hidden" name="impsol<?php echo $i;?>" value="<?php echo $row_qrysolicitudes['imptotal'];?>">
                  </div></td>
                  <td><?php if ( $row_qrysolicitudes['saldo'] == 0) { echo $row_qrysolicitudes['imptotal']; } else { echo $row_qrysolicitudes['saldo']; } ?>
                  <input type="hidden" name="impsolsaldo<?php echo $i;?>" value="<?php if ( $row_qrysolicitudes['saldo'] == 0) { echo $row_qrysolicitudes['imptotal']; } else { echo $row_qrysolicitudes['saldo'];}?>"></td>
                  <td>
                    <input name="ed<?php echo $i;?>" id="ed<?php echo $i;?>" type="text" class="cuadrodetextoJR" size="10" maxlength="15" value="<?php if ( $row_qrysolicitudes['saldo'] == 0) { echo $row_qrysolicitudes['imptotal']; } else { echo $row_qrysolicitudes['saldo']; } ?>" onBlur="CalcTotPagos(<?php echo $totalRows_qrysolicitudes;?>,'<?php echo $row_qrysolicitudes['id_solicitud'];?>')">
                    <input type="hidden" name="idsol<?php echo $i;?>" value="<?php echo $row_qrysolicitudes['id_solicitud'];?>"> 
                  </td>
                  <td><input name="chk<?php echo $i;?>" id="chk<?php echo $i;?>" type="checkbox" onClick="CalcTotPagos(<?php echo $totalRows_qrysolicitudes;?>,'<?php echo $row_qrysolicitudes['id_solicitud'];?>')" value=""></td>

                </tr>
                <?php $i++; } while ($row_qrysolicitudes = mysql_fetch_assoc($qrysolicitudes)); ?>
              </table>
                <table width="100%" border="0" align="center">
                  <tr class="contenido_columnas_tabla" align="center">
                    <td width="10%"><div align="right"></div></td>
                    <td width="12%">&nbsp;</td>
                    <td width="25%"><div align="left"></div></td>
                    <td width="15%"><div align="right">Totales: </div></td>
                    <td width="10%"><div align="right">                      <?php echo $row_qrysolicitudesTot['imptotalsol'];?>
					    <input type="hidden" name="totalrowsol" value="<?php echo $totalRows_qrysolicitudes;?>">
				      <input type="hidden" name="totsol" value="<?php echo $row_qrysolicitudesTot['imptotalsol'];?>">
                    </div></td>
                    <td width="10%">&nbsp;</td>
                    <td width="10%">                      <input name="totpagos" type="text" class="cuadrodetextoJR_sinbordes" size="10" readonly="true"></td>
                    <td width="3%">&nbsp;</td>
                  </tr>
                  <tr class="contenido_columnas_tabla" align="center">
                    <td height="16">&nbsp;</td>
                    <td>&nbsp;</td>
                    <td colspan="2"><div align="right">Importe a afectar: </div></td>
                    <td><input name="textfield2" type="text" class="cuadrodetextoJR_sinbordes" value="<?php echo $impsinafectar;?>" size="10"></td>
                    <td>&nbsp;</td>
                    <td>
                      <div align="center">
                        <input name="textfield" type="text" class="cuadrodetextoJR_sinbordes" value="<?php echo $impsinafectar;?>" size="10">
                      </div></td>
                    <td>&nbsp;</td>
                  </tr>
                  <tr class="contenido_columnas_tabla" align="center">
                    <td height="20">&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td><div align="right">Resto:</div></td>
                    <td><input name="textfield3" type="text" class="cuadrodetextoJR_sinbordes" size="10"></td>
                    <td>&nbsp;</td>
                    <td><input name="totresto" type="text" class="cuadrodetextoJR_sinbordes" id="totresto" size="10"></td>
                    <td>&nbsp;</td>
                  </tr>
                  <tr class="contenido_columnas_tabla" align="center">
                    <td height="37">&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td><input type="hidden" name="pagos_graba"></td>
                    <td>&nbsp;</td>
                    <td><input name="Submit3" type="button" class="botones" value="Grabar" onClick="ChkSelItem(<?php echo $totalRows_qrysolicitudes;?>,'<?php echo $row_qrypagos['id_pago'];?>')"></td>
                    <td>&nbsp;</td>
                  </tr>
                </table>
                <br>
                <?php } // Show if recordset not empty ?>
			</form>
          <!-- InstanceEndEditable --></td>
        </tr>
      </table>
    </td>
  </tr>
</table>
</body>
<!-- InstanceEnd --></html>
